<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-input v-model="queryParams.keyword" placeholder="请输入关键词进行搜索" class="input-with-select">
      <template #append>
        <el-button type="primary" @click="handleFormQuery">搜索</el-button>
      </template>
    </el-input>
    <DynamicForm
      ref="queryRef"
      v-model="queryParams"
      :config="formConfig"
      :items="formItems"
      :inline="true"
      @submit="handleFormQuery"
      @reset="resetQuery">
      <template #dateRange1="{ formData }">
        <el-date-picker
          v-model="dateRange1"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 18vw" />
      </template>
      <template #dateRange2="{ formData }">
        <el-date-picker
          v-model="dateRange2"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 18vw" />
      </template>
    </DynamicForm>

    <!-- 图表展示区域 -->
    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 案件列表区域 -->
        <div class="case-list" v-loading="loading">
          <div v-for="(item, index) in caseList" :key="index" class="case-item">
            <el-card class="case-card">
              <div class="case-header">
                <h3 class="case-title">
                  {{ item.caseNumber }} {{ item.companyName }}
                  <el-tag class="case-status" :type="['info', 'success', 'warning'][Number(item.status)]">
                    {{ statusMap.find(status => status.value === item.status)?.label }}
                  </el-tag>
                </h3>
              </div>
              <div class="case-content">
                <p class="case-description">{{ item.description }}</p>
                <p class="case-detail">{{ item.detail }}</p>
                <p class="case-info">
                  <span class="blue">承办人：{{ item.handler }}</span>
                  相关案件：{{ item.relatedCases.join(' ') }}
                </p>
              </div>
              <div class="case-footer">
                <el-button type="primary" @click="handleQuery(item)">查看</el-button>
                <el-button @click="handleBorrow(item)">借阅</el-button>
              </div>
            </el-card>
          </div>

          <!-- 分页器 -->
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList" />
        </div>
      </el-col>
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>案件来源分析</span>
            </div>
          </template>
          <div ref="sourceChartRef" style="height: 300px"></div>
        </el-card>
        <el-card>
          <template #header>
            <div class="card-header">
              <span>年份分布</span>
            </div>
          </template>
          <div ref="yearChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 借阅弹窗 -->
    <el-dialog title="借阅申请" v-model="borrowShow" width="700px">
      <DynamicForm ref="queryRef" v-model="formData" :config="formConfigBorrow" :items="formItemsDetail">
        <template #dateRange="{ item }">
          <el-date-picker
            v-model="formData.dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :style="item.style" />
        </template>
        <template #year="{ item }">
          <el-date-picker v-model="formData.year" type="year" placeholder="请选择" :style="item.style" />
        </template>
      </DynamicForm>
      <template #footer>
        <el-button @click="borrowShow = false">取消</el-button>
        <el-button type="primary" @click="handleBorrowSubmit">提交申请</el-button>
      </template>
    </el-dialog>
    <el-dialog title="案件详情" v-model="open" width="1200px">
      <div class="similarStatus">
        <el-tag size="large">状态</el-tag>
      </div>
      <el-row :gutter="20">
        <el-col :span="16">
          <DynamicForm
            ref="queryRef"
            v-model="formDataDetail"
            :config="formConfigDetail"
            :items="formDetailItems"
            :dict-data="{ case_source }">
            <template #caseId="{ item }">
              <el-select v-model="formDataDetail.caseId" placeholder="请选择立案号" clearable @change="handleCase">
                <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </DynamicForm>
        </el-col>
        <el-col :span="8" style="padding-top: 40px">
          <label>相似案件：</label>
          <ul class="similarList">
            <li v-for="(item, index) in similarCaseList" :key="index" @click="handleSeeCase(item)">
              {{ item.caseCause }}
            </li>
          </ul>
        </el-col>
      </el-row>
      <div class="form-title-wrapper" style="margin-bottom: 0">
        <div class="form-title-text">案卷附件</div>
      </div>
      <!-- 附件 -->
      <FileList :fileUploadList="formDataDetail.filesList" :showTitle="false" />
      <div class="form-title-wrapper">
        <div class="form-title-text">借阅记录</div>
      </div>
      <Table v-loading="loading" :data="tableData" :columns="newColumns" border />
      <template #footer>
        <div class="form-footer">
          <el-button type="primary" @click="handleSimilarConfirm">借阅</el-button>
          <el-button @click="() => (open = false)">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, nextTick, getCurrentInstance } from 'vue'
import DynamicForm from '@/components/DynamicForm/index.vue'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pageConfig } from './config'
import FileList from '@/components/FileList/index.vue'
import Table from '@/components/Table'

const { proxy } = getCurrentInstance()

const { case_source } = proxy.useDict('case_source')

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  partyName: '',
  handler: '',
  startTime: '',
  endTime: '',
})

const { formConfig, formItems, formConfigBorrow, formItemsDetail, formConfigDetail, formDetailItems, newColumns } =
  pageConfig()

const dateRange1 = ref([])
const dateRange2 = ref([])
const loading = ref(false)
const total = ref(400)
const sourceChartRef = ref()
const yearChartRef = ref()

// 案件列表数据
const statusMap = [
  { value: '0', label: '未借阅' },
  { value: '1', label: '已借阅' },
]
const caseList = ref([
  {
    caseNumber: '京环监察立〔2022〕184号',
    companyName: '北京甲乙有限公司',
    status: '0',
    description:
      '涉嫌"利用渗井、渗坑、裂缝、溶洞，私设暗管，篡改、伪造监测数据，或者不正常运行水污染防治设施等逃避监管的方式排放水污染物"案...',
    detail:
      '2022年10月26日，北京市生态环境执法大队执法人员会对该单位现场检查，发现该公司污水处理站东侧设置有一根三通管，该三通管连接企业污水排放管道...',
    handler: '刘青天',
    relatedCases: ['环境监察立〔2022〕184号', '京环境监察立〔2022〕184号'],
  },
  {
    caseNumber: '京环监察立〔2022〕184号',
    companyName: '北京甲乙有限公司',
    status: '1',
    description:
      '涉嫌"利用渗井、渗坑、裂缝、溶洞，私设暗管，篡改、伪造监测数据，或者不正常运行水污染防治设施等逃避监管的方式排放水污染物"案...',
    detail:
      '2022年10月26日，北京市生态环境执法大队执法人员会对该单位现场检查，发现该公司污水处理站东侧设置有一根三通管，该三通管连接企业污水排放管道...',
    handler: '刘青天',
    relatedCases: ['环境监察立〔2022〕184号', '京环境监察立〔2022〕184号'],
  },
])

// 初始化饼图
const initSourceChart = () => {
  const sourceChart = echarts.init(sourceChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
    },
    series: [
      {
        name: '案件来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '40',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 356, name: '本部' },
          { value: 124, name: '户籍网' },
          { value: 232, name: '未回应' },
        ],
      },
    ],
  }
  sourceChart.setOption(option)
}

// 初始化柱状图
const initYearChart = () => {
  const yearChart = echarts.init(yearChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    xAxis: {
      type: 'category',
      data: ['2021', '2022', '2023', '2024', '2025'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: [150, 230, 224, 218, 135],
        type: 'bar',
      },
    ],
  }
  yearChart.setOption(option)
}

// 查询列表
const getList = () => {
  loading.value = true
  // 这里添加实际的API调用
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

// 搜索表单查询
const handleFormQuery = () => {
  queryParams.value.pageNum = 1
  console.log('查询', queryParams.value)
  getList()
}

// 重置
const resetQuery = () => {
  dateRange1.value = []
  dateRange2.value = []
  queryParams.value.partyName = ''
  queryParams.value.handler = ''
  queryParams.value.startTime = ''
  queryParams.value.endTime = ''
  handleFormQuery()
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 查询案件
const open = ref(false)
const handleQuery = (item: any) => {
  ElMessage.success(`查询案件：${item.caseNumber}`)
  open.value = true
  handleCaseList()
  setTimeout(() => {
    queryRef.value.resetValidation()
  }, 200)
}

// 借阅操作
const handleBorrow = (item: any) => {
  borrowShow.value = true
  setTimeout(() => {
    queryRef.value.resetValidation()
  }, 200)
}

// 借阅弹窗
const borrowShow = ref(false)
const queryRef = ref<any>(null)
const formData = ref({
  dateRange: [],
  year: '',
})

const handleBorrowSubmit = () => {
  queryRef.value.validate().then(valid => {
    if (valid) {
      console.log(formData.value)
    }
  })
}

// 案件详情弹窗
const formDataDetail = ref({
  caseId: '',
  filesList: [],
})
const similarCaseList = ref([{ caseCause: '环境污染案' }, { caseCause: '非法排污案' }, { caseCause: '水污染防治案' }])

const handleCase = (val: any) => {
  console.log(val)
}
const numberList = ref([])
async function handleCaseList() {
  // const res = await getCaseList()
  // numberList.value = res.data.map(item => ({
  //   label: item.caseNo,
  //   value: item.id,
  // }))
}

const handleSeeCase = caseItem => {
  console.log('查看案件：', caseItem)
}

// 借阅记录
const tableData = ref([])

// 借阅按钮
const handleSimilarConfirm = () => {
  borrowShow.value = true
  setTimeout(() => {
    queryRef.value.resetValidation()
  }, 200)
}

onMounted(() => {
  getList()
  initSourceChart()
  initYearChart()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}
.input-with-select {
  width: 60%;
  margin-left: 50%;
  transform: translate(-50%, 0);
  margin-bottom: 30px;
  margin-top: 10px;

  :deep(.el-input__wrapper) {
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    padding: 4px 8px;
    border-radius: 10px 0 0 10px;

    &:hover,
    &.is-focus {
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
    }
  }

  :deep(.el-input__inner) {
    font-size: 15px;
    height: 42px;
    &::placeholder {
      font-size: 14px;
    }
  }

  :deep(.el-input-group__append) {
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
    border-radius: 0 10px 10px 0;
    .el-button {
      color: white;
      border: none;
      height: 100%;
      &:hover {
        background-color: var(--el-color-primary-light-3);
        opacity: 0.9;
      }
    }
  }
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.case-list {
  // margin-top: 20px;
}
.case-item {
  margin-bottom: 20px;
}
.case-card {
  border-radius: 4px;
}
.case-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}
.case-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
}
.case-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: normal;
}
.case-content {
  padding: 15px 0;
  color: #606266;
  font-size: 14px;
}
.case-description {
  margin-bottom: 10px;
  line-height: 1.6;
}
.case-detail {
  margin-bottom: 10px;
  line-height: 1.6;
}
.case-info {
  color: #909399;
  margin: 0;
  .blue {
    color: #409eff;
    margin-right: 10px;
  }
}
.case-footer {
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.pagination-info {
  text-align: center;
  margin: 15px 0;
  color: #606266;
  font-size: 14px;
}
.similarStatus {
  position: absolute;
  right: 30px;
}
.similarList {
  list-style-type: none;
  padding-left: 20px;
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  padding: 10px;
  li {
    margin-bottom: 6px;
    color: #409eff;
    cursor: pointer;
    &:last-child {
      margin-bottom: 0;
    }
    &:hover {
      text-decoration: underline;
      color: #66b1ff;
    }
  }
}
</style>
